package org.example.pg;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Timestamp;
import java.util.Random;

public class InsertProductData {
    public static void main(String[] args) {
        String url = "jdbc:postgresql://192.168.99.201:5432/postgres";
        String username = "postgres";
        String password = "hyh.5795";

        try (Connection conn = DriverManager.getConnection(url, username, password)) {
            String tableName = "product_heap_100";
            String sql = String.format("INSERT INTO %s (name, category, price, stock) VALUES (?, ?, ?, ?)",tableName);
            PreparedStatement pstmt = conn.prepareStatement(sql);

            Random random = new Random();
            int batchSize = 1000; // 每次批量插入的记录数
            int totalRecords = 1000000; // 总共插入的记录数

            conn.setAutoCommit(false);

            long startTime = System.currentTimeMillis();

            for (int i = 1; i <= totalRecords; i++) {
                pstmt.setString(1, "Product " + i); // name
                pstmt.setString(2, "Category " + (random.nextInt(10) + 1)); // category
                pstmt.setBigDecimal(3, new java.math.BigDecimal(random.nextDouble() * 1000).setScale(2, java.math.BigDecimal.ROUND_HALF_UP)); // price
                pstmt.setInt(4, random.nextInt(1000)); // stock

                pstmt.addBatch();

                if (i % batchSize == 0) {
                    pstmt.executeBatch();
                    conn.commit();
                }
            }

            // 执行剩余的批量操作
            pstmt.executeBatch();
            conn.commit();

            long endTime = System.currentTimeMillis();
                System.out.println("Inserted table: " +tableName+" total count:" +totalRecords + " records in " + (endTime - startTime) / 1000.0 + " seconds.");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
